//引入 mongoose 模块
var mongoose = require("mongoose");

//链接数据库
mongoose.connect("mongodb://todoapp:todoapp123@ds035787.mlab.com:35787/nodejs_todo",
    {useNewUrlParser:true},
    function(err){
        if(err){
            console.log('Connection Error:' + err)
        }else{
            console.log('Connection success!')
        }
    });

//创建图表
var todoSchema = new mongoose.Schema({
    item:String
});

//往数据库中存储数据
var Todo = mongoose.model("Todo",todoSchema);

var bodyParser = require("body-parser");
//对数据进行解析
var urlencodeParser = bodyParser.urlencoded({extended:false});

// var data=[
//     {item:"欢迎大家来到蓝鸥课堂1"},
//     {item:"欢迎大家来到蓝鸥课堂2"},
//     {item:"欢迎大家来到蓝鸥课堂3"}
// ];

module.exports = function (app) {

    //获取数据
    app.get("/todo",function (req,res) {
        // res.send( '您访问的路径是：'+ req.url);
        Todo.find({}, function (err, data) {
            if (err) throw err;
            res.render("todo", {todos: data});
        });
    });

    //传递数据
    app.post("/todo",urlencodeParser,function (req,res) {
        // data.push(req.body);
        Todo(req.body).save(function (err,data) {
            if(err) throw err;
            res.json(data);
        });
        // res.json(data);
    })

    //删除数据
    app.delete("/todo/:item",function (req,res) {
        var item = req.params.item;
        Todo.find({item:item}).deleteOne(function (err,data) {
            if(err) throw err;
            res.json(data);
        })
        // data = data.filter(function (todo) {
        //     return todo.item != item;
        // });
    })
}